<template>
<nav class="site-navbar" :class="'site-navbar--' + navbarLayoutType">
  <div class="site-navbar__header">
    <h1 class="site-navbar__brand" @click="$router.push({ name: 'home' })">
      <a class="site-navbar__brand-lg" href="javascript:;">智慧生活平台</a>
      <a class="site-navbar__brand-mini" href="javascript:;">智慧</a>
    </h1>
  </div>
  <div class="site-navbar__body clearfix">
    <el-menu class="site-navbar__menu" mode="horizontal">
      <el-menu-item class="site-navbar__switch" index="0" @click="sidebarFold = !sidebarFold">
        <icon-svg name="zhedie"></icon-svg>
      </el-menu-item>
      <el-menu-item index="2" class="school_size">
        <div v-if="showSystemUnit()" id="dls_css">
          <el-dropdown @command="changeAgent">
            <a @click="goBackUnit(1)">
              {{systemUnitName}}
              <span v-show="showAgentUnit()">&nbsp;&nbsp;/</span>
            </a>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item disabled>代理商列表</el-dropdown-item>
              <el-dropdown-item v-for="item in agentList" v-text="item.unitName" :command="item" :key="item.unitGuid" :value="item.value" :divided="item.divided" :disabled="item.disabled"></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!--  系统单位  -->
        </div>
        <div v-if="showAgentUnit()" id="dls_css">
          <el-dropdown @command="changeSchool">
            <a @click="goBackUnit(50)">
              {{agentName}}
              <span v-show="showSchool()">&nbsp;&nbsp;/</span>
            </a>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item disabled>学校列表</el-dropdown-item>
              <el-dropdown-item v-for="item in schoolDropDownList" v-text="item.unitName" :command="item" :key="item.unitGuid" :value="item.value" :divided="item.divided" :disabled="item.disabled"></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!--  代理商单位  -->
        </div>
        <div v-if="showSchool()">
          <a @click="goBackUnit(100)" id="schoolname">{{schoolName}}</a>
          <!--  学校  -->
        </div>
      </el-menu-item>
    </el-menu>
    <el-menu class="site-navbar__menu site-navbar__menu--right" mode="horizontal">
      <el-menu-item v-if="setSwitchAgentEnable()" index="1" @click="switchAgent()">
        <template slot="title">
          <el-badge value="代理商" type="primary">
            <icon-svg name="qiehuan" class="el-icon-setting"></icon-svg>
          </el-badge>
        </template>
      </el-menu-item>
      <el-menu-item index="1" @click="switchSchool()">
        <template slot="title">
          <el-badge value="学校" type="primary">
            <icon-svg name="qiehuan" class="el-icon-setting"></icon-svg>
          </el-badge>
        </template>
      </el-menu-item>
      <el-menu-item class="site-navbar__avatar" index="3">
        <el-dropdown :show-timeout="0" placement="bottom">
          <span class="el-dropdown-link">
            <icon-svg name="admin" class="site-sidebar__menu-icon"></icon-svg>
            {{ username }}
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="checkBgcolor()">切换主题</el-dropdown-item>
            <el-dropdown-item @click.native="logoutHandle()">退出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-menu-item>
    </el-menu>
  </div>
  <!-- 弹窗, 切换代理商 -->
  <switch-agent v-if="switchAgentVisible" ref="switchAgent"></switch-agent>
  <!-- 弹窗, 切换学校 -->
  <switch-school v-if="switchSchoolVisible" ref="switchSchool"></switch-school>
  <!-- 弹窗, 修改密码 -->
  <update-password v-if="updatePassowrdVisible" ref="updatePassowrd"></update-password>
</nav>
</template>

<script>
import UpdatePassword from "./main-navbar-update-password";
import SwitchSchool from "./unit-manage/switch-school";
import SwitchAgent from "./unit-manage/switch-agent";
import {
  clearLoginInfo
} from "@/utils";
import {
  resetRouter
} from "@/router/restrouter";
export default {
  data() {
    return {
      updatePassowrdVisible: false,
      switchSchoolVisible: false,
      switchAgentVisible: false,
      userGuid: "",
      allschoollist: [],
      pageNum: 1,
      pageSize: 10,
      recordCount: 0,
      currentPage: 1,
      searchInfo: {},
      agentList: [],
      schoolDropDownList: [],
      showunitType: 0,
    };
  },
  components: {
    UpdatePassword,
    SwitchSchool,
    SwitchAgent,
  },
  created() {
    this.username = sessionStorage.getItem("username");
    this.userGuid = sessionStorage.getItem("administrator");
    this.userType = sessionStorage.getItem("userType");
    this.unitType = this.$store.state.user.unitType;
    this.showunitType = this.$store.state.user.unitType;
    this.getSchoolList();
  },
  mounted() {
    if (this.isSysAdmin(this.userType)) {
      this.getAgentList();
    }
    if (this.isAgent(this.userType)) {
      this.getSchoolList(); // 代理商第一次进来需要加载
    }
  },
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid;
      },
    },
    navbarLayoutType: {
      get() {
        return this.$store.state.common.navbarLayoutType;
      },
    },
    sidebarFold: {
      get() {
        return this.$store.state.common.sidebarFold;
      },
      set(val) {
        this.$store.commit("common/updateSidebarFold", val);
      },
    },
    mainTabs: {
      get() {
        return this.$store.state.common.mainTabs;
      },
      set(val) {
        this.$store.commit("common/updateMainTabs", val);
      },
    },
    userName: {
      get() {
        return this.$store.state.user.name;
      },
    },
    changeschoolname: {
      get() {
        return this.$store.state.user.changeschoolname;
      },
    },
    systemUnitName: {
      get() {
        return this.$store.state.user.sysUnitName;
      },
    },
    agentName: {
      get() {
        return this.$store.state.user.agentName;
      },
    },
    schoolName: {
      get() {
        return this.$store.state.user.schoolName;
      },
    },
  },
  watch: {
    "$store.state.user.agentGuid": function (newFlag, oldFlag) {
      // 监听当前的代理商，如果有改变则重新加载代理商的学校
      if (newFlag && newFlag !== "") {
        this.getSchoolList();
      }
    },
    "$store.state.user.sysUnitGuid": function (newFlag, oldFlag) {
      // 监听当前的代理商，如果有改变则重新加载代理商的学校
      if (newFlag && newFlag !== "") {
        this.getAgentList();
      }
    },
  },
  methods: {
    // 切换主题
    checkBgcolor() {
      this.$router.push({
        path: "/theme"
      });
    },
    // 是否显示系统单位
    showSystemUnit() {
      if (this.isSysAdmin(this.userType)) {
        // 当前为系统用户，可查看系统单位，其他身份则不能查看
        return true;
      }
      return false;
    },

    // 是否显示代理商单位
    showAgentUnit() {
      if (this.isUnitUser(this.userType)) {
        // 如果是单位用户，不能看代理商
        return false;
      }

      if (this.isSystemUnit(this.$store.state.user.unitType)) {
        // 当前为系统单位，则隐藏代理商单位
        return false;
      }

      return true;
    },

    // 是否显示学校
    showSchool() {
      if (this.isOrdinaryUnit(this.$store.state.user.unitType)) {
        // 当前显示的学校，则显示，否则其他一律不显示
        return true;
      }

      return false;
    },

    // 跳转单位
    goBackUnit(unitType) {
      this.showunitType = unitType;
      var switchGuid = null;
      var switchName = null;
      var switchType = unitType;
      if (this.isSystemUnit(unitType)) {
        switchGuid = this.$store.state.user.sysUnitGuid;
        switchName = this.$store.state.user.sysUnitName;
      } else if (this.isAgentUnit(unitType)) {
        switchGuid = this.$store.state.user.agentGuid;
        switchName = this.$store.state.user.agentName;
        this.getSchoolList();
      } else if (this.isOrdinaryUnit(unitType)) {
        switchGuid = this.$store.state.user.schoolGuid;
        switchName = this.$store.state.user.schoolName;
        // this.goBackUnit(100)
      } else {
        this.$message.error("操作异常！");
      }

      if (switchGuid) {
        sessionStorage.setItem("unitType", unitType);
        // 存储unitGuid到session
        sessionStorage.setItem("unitGuid", switchGuid);
        sessionStorage.setItem("unitName", switchName);
        this.$store.commit("user/updateSelectedUnigInfo", {
          unitType: switchType,
          unitGuid: switchGuid,
          unitName: switchName,
        });
        this.mainTabs = [];
        this.menuActiveName = "";
        this.$router.options.isAddDynamicMenuRoutes = false;
        this.$router.push({
          name: "home",
          query: {
            type: unitType
          }
        });
        setTimeout(() => {
          this.$store.commit(
            "common/updateMenuList",
            JSON.parse(sessionStorage.getItem("menuList") || "[]")
          );
          this.$store.commit(
            "common/updateDynamicMenuRoutes",
            JSON.parse(sessionStorage.getItem("dynamicMenuRoutes") || "[]")
          );
          this.$router.push({
            path: "/"
          });
        }, 500)
      }
    },
    // 弹窗切换学校
    switchSchool() {
      this.switchSchoolVisible = true;
      this.$nextTick(() => {
        this.$refs.switchSchool.init();
      });
    },
    //弹窗切换代理商
    switchAgent() {
      this.switchAgentVisible = true;
      this.$nextTick(() => {
        this.$refs.switchAgent.init();
      });
    },

    // 设置切换代理商按钮是否可用
    setSwitchAgentEnable() {
      if (this.isSysAdmin(this.userType)) {
        return true;
      }
      return false;
    },
    // 退出
    logoutHandle() {
      this.$confirm(`确定进行[退出]操作?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          // 删除用户信息cookie
          document.cookie = "shujuxiaoyuan_user=;max-age=-1";
          this.mainTabs = [];
          this.menuActiveName = "";
          sessionStorage.clear();

          //resetRouter();
          // 重置vuex
          this.$store.commit("resetStore", "");
          this.$router.options.isAddDynamicMenuRoutes = false;
          this.$router.push({
            name: "login"
          });
          //location.reload();
        })
        .catch(() => {});
    },

    // 获取代理商
    getAgentList() {
      this.searchInfo.agentGuid = this.userGuid;
      this.searchInfo.unitType = 50; // 代理商单位
      this.searchInfo.unitGuid = this.$store.state.user.changeschoolid;
      this.$http({
        url: this.$http.adornUrl("/manager/unit-info-page"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            pageNum: 1,
            pageSize: 20,
            searchInfo: this.searchInfo,
          },
          messageType: this.messageType,
        }),
      }).then(({
        data
      }) => {
        if (data.messageCode == 200) {
          this.agentList = data.messageContent.data;
          if (data.messageContent.recordCount <= data.messageContent.pageSize) {
            // 当前已显示完
            this.agentList.push({
              unitGuid: "no-more",
              unitName: "共" + data.messageContent.recordCount + "个",
              divided: true,
              disabled: true,
            });
          } else {
            // 没有显示完，需要展示开显示更过
            this.agentList.push({
              unitGuid: "more",
              unitName: "更多",
              divided: true,
            });
          }
        } else {
          this.$message.error(data.errorMessage);
        }
      });
    },
    // 获取学校
    getSchoolList() {
      this.searchInfo.agentGuid = this.userGuid;
      this.searchInfo.unitType = 100; // 学校
      this.searchInfo.unitGuid = this.$store.state.user.changeschoolid;
      this.$http({
        url: this.$http.adornUrl("/manager/unit-info-page"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            pageNum: 1,
            pageSize: 20,
            searchInfo: this.searchInfo,
          },
          messageType: this.messageType,
        }),
      }).then(({
        data
      }) => {
        if (data.messageCode == 200) {
          this.schoolDropDownList = data.messageContent.data;
          if (data.messageContent.recordCount <= data.messageContent.pageSize) {
            // 当前已显示完
            this.schoolDropDownList.push({
              unitGuid: "no-more",
              unitName: "共" + data.messageContent.recordCount + "个",
              divided: true,
              disabled: true,
            });
          } else {
            // 没有显示完，需要展示开显示更过
            this.schoolDropDownList.push({
              unitGuid: "more",
              unitName: "更多",
              divided: true,
            });
          }
        } else {
          this.$message.error(data.errorMessage);
        }
      });
    },
    changeAgent(row) {
      console.log(row);
      if (row.unitGuid == "more") {
        // 弹出显示更多代理商
        this.switchAgent();
        return;
      }
      if (row.unitGuid.length != 36) {
        this.$message.error("数据异常");
        return;
      }
      this.$store.commit("user/updateSelectedUnigInfo", {
        unitType: 50,
        unitGuid: row.unitGuid,
        unitName: row.unitName,
      });
      this.goBackUnit(50);
    },
    changeSchool(row) {
      if (row.unitGuid == "more") {
        // 弹出显示更多学校
        this.switchSchool();
        return;
      }
      if (row.unitGuid.length != 36) {
        this.$message.error("数据异常");
        return;
      }
      this.$store.commit("user/updateSelectedUnigInfo", {
        unitType: 100,
        unitGuid: row.unitGuid,
        unitName: row.unitName,
      });
      this.goBackUnit(100);
    },
  },
};
</script>

<style lang="scss" scoped>
@import '../assets/scss/_variables';

.el-badge {
  /deep/.el-badge__content {
    background-color: $--color-primary;
  }
}

.el-menu--horizontal>.el-menu-item {
  color: #303133;
}

.school_size {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

#schoolname {
  font-size: 14px;
  color: #606266;
}

#dls_css {
  margin-right: 10px;
}
</style>
